﻿using System;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Http;
using ELearning.BLL;
using ELearning.Common;
using ELearning.Common.CommonStr;
using ELearning.Common.Extensions;
using ELearning.Common.Helpers;
using ELearning.Common.Model;
using ELearning.Models;
using ELearning.Models.ViewModel.YTJYAdmin.Course;

namespace ELearning.API.Controllers.YTJYAdminController
{
    /// <summary>
    /// 课程章节相关控制器
    /// </summary>
    public class ChapterController : BaseApiController
    {
        /// <summary>
        /// 章节操作service
        /// </summary>
        private TChapterService tChapterService => new TChapterService();

        /// <summary>
        /// 章节试卷关联操作service
        /// </summary>
        private RChapterPaperService rChapterPaperService => new RChapterPaperService();

        /// <summary>
        /// 章节视频关联操作service
        /// </summary>
        private RChapterVideoLibService rChapterVideoLibService => new RChapterVideoLibService();

        /// <summary>
        /// 视频库相关操作server
        /// </summary>
        private EVideoLibService eVideoLibService => new EVideoLibService();

        /// <summary>
        /// 课程操作service
        /// </summary>
        private ECourseService eCourseService => new ECourseService();

        /// <summary>
        /// 获取列表
        /// </summary>
        [HttpPost, Route("api/ytjyadmin/EChapter/GetModelList")]
        public ServiceResponse<ChapterViewModel> GetModelList(ChapterRequest request)
        {
            Expression<Func<TChapter, bool>> whereLamdba = c => c.IsDelete == false && c.CourseId == request.CourseId;
            if (!string.IsNullOrEmpty(request.Name))
                whereLamdba = whereLamdba.And(c => c.Name.Contains(request.Name));
            var models = tChapterService.FindList(whereLamdba);

            var viewModel = new ChapterViewModel { TotalCount = models.Count() };

            if (models.Any())
            {
                var ids = models.Select(m => m.Id).ToList();
                var videos = rChapterVideoLibService.FindList(r => !r.IsDelete && ids.Contains(r.ChapterId)).ToList();
                var papers = rChapterPaperService.FindList(r => !r.IsDelete && ids.Contains(r.ChapterId)).ToList();
                foreach (var chapter in models)
                {
                    var v = chapter.MapTo<ChapterItem, TChapter>();
                    v.UpdateTime = chapter.UpdateTime.ToCommonStr();
                    v.VideoLibId = videos.FirstOrDefault(r => r.ChapterId == chapter.Id)?.VideoLibId ?? Guid.Empty;
                    v.PaperId = papers.FirstOrDefault(r => r.ChapterId == chapter.Id)?.PaperId ?? Guid.Empty;
                    viewModel.Items.Add(v);
                }

                viewModel.Items = viewModel.Items.OrderBy(x => x.Sort).ToList();
            }

            return ServiceResponse<ChapterViewModel>.SuccessResponse(CommonConst.OprateSuccessStr, viewModel);
        }

        /// <summary>
        /// 新增或者更新视频信息
        /// </summary>
        [HttpPost, Route("api/ytjyadmin/EChapter/AddModel")]
        public ServiceResponse<bool> AddModel(ChapterAddModel viewModel)
        {
            if (viewModel.IsNotNull() && viewModel.Items.IsNotNull() && viewModel.Items.Any())
            {
                var course = eCourseService.Find(c => !c.IsDelete && c.Id == viewModel.CourseId);
                if (course.IsNotNull())
                {
                    var sort = tChapterService.FindList(x => !x.IsDelete && x.CourseId == course.Id).OrderByDescending(x => x.Sort).ThenBy(x => x.CreateTime).FirstOrDefault()?.Sort ?? 0;
                    foreach (var video in viewModel.Items)
                    {
                        #region 添加视频

                        var model = new EVideoLib
                        {
                            UpdateTime = DateTime.Now,
                            UpdateUserId = CurrentUserModel.UserId,
                            CreateTime = DateTime.Now,
                            CreateUserId = CurrentUserModel.UserId,
                            Id = Guid.NewGuid(),
                            OrgCode = CurrentUserModel.OrgCode ?? string.Empty,
                            CategoryId = course.CategoryId,
                            TypeCode = course.TypeCode,
                            CoverUrl = string.Empty,
                            ConvertVideoNote = string.Empty,
                            IsDelete = false,
                            Sort = 0,
                            Name = video.Name,
                            Status = 1,
                            FileId = video.FileId,
                            Description = video.Name,
                            DownloadUrl = video.DownloadUrl,
                            Size = video.Size,
                            Duration = 0,
                            PlayUrl0 = string.Empty,
                            PlayUrl1 = string.Empty,
                            PlayUrl2 = string.Empty,
                            PlayUrl3 = string.Empty
                        };

                        if (!string.IsNullOrEmpty(model.FileId) && !string.IsNullOrEmpty(model.DownloadUrl))
                        {
                            model.Status = 2;
                            var res = TencentCloudHelper.StartConvertVideo(model.FileId);
                            model.ConvertVideoNote = res;
                        }
                        eVideoLibService.AddNoSaveChange(model);

                        #endregion

                        #region 添加章节

                        var chapter = new TChapter
                        {
                            UpdateTime = DateTime.Now,
                            UpdateUserId = CurrentUserModel.UserId,
                            CreateTime = DateTime.Now,
                            CreateUserId = CurrentUserModel.UserId,
                            Id = Guid.NewGuid(),
                            CourseId = viewModel.CourseId,
                            Description = video.Name,
                            IsDelete = false,
                            Name = video.Name,
                            OrgCode = model.OrgCode,
                            Sort = ++sort,
                            PassGrade = 0
                        };
                        tChapterService.AddNoSaveChange(chapter);

                        #endregion

                        #region 关联视频与小节

                        var rcv = new RChapterVideoLib
                        {
                            Id = Guid.NewGuid(),
                            ChapterId = chapter.Id,
                            CourseId = viewModel.CourseId,
                            CreateTime = DateTime.Now,
                            CreateUserId = CurrentUserModel.UserId,
                            IsDelete = false,
                            VideoLibId = model.Id,
                            Sort = 0,
                            UpdateTime = DateTime.Now,
                            UpdateUserId = CurrentUserModel.UserId
                        };
                        rChapterVideoLibService.AddNoSaveChange(rcv);

                        #endregion
                    }
                    eVideoLibService.SaveChange();
                }
            }

            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, true);
        }


        /// <summary>
        /// 新增或者更新信息
        /// </summary>
        [HttpPost, Route("api/ytjyadmin/EChapter/PostModel")]
        public ServiceResponse<bool> PostModel(ChapterPostModel viewModel)
        {
            var model = tChapterService.Find(v => v.Id == viewModel.Id);

            //章节名称为空则默认为视频名称
            if (string.IsNullOrEmpty(viewModel.Name))
            {
                var video = eVideoLibService.Find(v => v.Id == viewModel.VideoLibId);
                if (video.IsNotNull())
                {
                    viewModel.Name = video.Name;
                }
            }

            if (model.IsNotNull())//编辑
            {
                model.Name = viewModel.Name;
                model.Description = viewModel.Description;
                model.Sort = viewModel.Sort;
                model.UpdateTime = DateTime.Now;
                model.UpdateUserId = CurrentUserModel.UserId;

                tChapterService.UpdateNoSaveChange(model);
            }
            else//新增
            {
                model = viewModel.MapTo<TChapter, ChapterPostModel>();

                model.UpdateTime = DateTime.Now;
                model.UpdateUserId = CurrentUserModel.UserId;
                model.CreateTime = DateTime.Now;
                model.CreateUserId = CurrentUserModel.UserId;
                model.Id = Guid.NewGuid();

                tChapterService.AddNoSaveChange(model);
            }

            #region 关联试卷

            var deleteList = rChapterPaperService.FindList(r => !r.IsDelete && r.ChapterId == model.Id).ToList();
            if (deleteList.Any())
                rChapterPaperService.DeletesNoSaveChange(deleteList);
            if (viewModel.PaperId != Guid.Empty)
            {
                var rcp = new RChapterPaper
                {
                    Id = Guid.NewGuid(),
                    ChapterId = model.Id,
                    CourseId = viewModel.CourseId,
                    CreateTime = DateTime.Now,
                    CreateUserId = CurrentUserModel.UserId,
                    IsDelete = false,
                    PaperId = viewModel.PaperId,
                    Sort = 0,
                    UpdateTime = DateTime.Now,
                    UpdateUserId = CurrentUserModel.UserId
                };
                rChapterPaperService.AddNoSaveChange(rcp);
            }

            #endregion

            #region 关联视频

            var deleteVideoList = rChapterVideoLibService.FindList(r => !r.IsDelete && r.ChapterId == model.Id).ToList();
            if (deleteVideoList.Any())
                rChapterVideoLibService.DeletesNoSaveChange(deleteVideoList);
            if (viewModel.VideoLibId != Guid.Empty)
            {
                var rcv = new RChapterVideoLib
                {
                    Id = Guid.NewGuid(),
                    ChapterId = model.Id,
                    CourseId = viewModel.CourseId,
                    CreateTime = DateTime.Now,
                    CreateUserId = CurrentUserModel.UserId,
                    IsDelete = false,
                    VideoLibId = viewModel.VideoLibId,
                    Sort = 0,
                    UpdateTime = DateTime.Now,
                    UpdateUserId = CurrentUserModel.UserId
                };
                rChapterVideoLibService.AddNoSaveChange(rcv);
            }

            #endregion

            tChapterService.SaveChange();
            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, true);
        }

        /// <summary>
        /// 删除
        /// </summary>
        [HttpGet, Route("api/ytjyadmin/EChapter/DeleteModel")]
        public ServiceResponse<bool> DeleteModel(Guid id)
        {
            var model = tChapterService.Find(v => v.Id == id);

            if (model.IsNotNull())
            {
                model.IsDelete = true;
                model.UpdateTime = DateTime.Now;
                model.UpdateUserId = CurrentUserModel?.UserId ?? Guid.Empty;
                tChapterService.Update(model);
            }

            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, true);
        }

    }
}